from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from rest_framework.viewsets import ModelViewSet
from .serializer import UserSerializer
# Create your views here.


# 用户注册
class UserRegister(APIView):
    def post(self, request):
        try:
            username = request.data.get('username')
            pwd = request.data.get('pwd')
            account = request.data.get('account')
            mobile = request.data.get('mobile')
            age = request.data.get('age')
            sex = request.data.get('sex')

            if not all([username,pwd,account,mobile,age,sex]):
                return Response({'code':204, 'message':'用户信息不完整'})

            User.objects.create(name=username,pwd=pwd,account=account,mobile=mobile,age=age,sex=sex)
            return Response({'code':200, 'message':'注册成功'})
        except Exception as e:
            print('错误>>>>', e)
            return Response({"code":500, "message":'服务器出错了'})


# 用户登录
class UserLogin(APIView):
    def post(self, request):
        try:
            username = request.data.get('username')
            pwd = request.data.get('pwd')

            user = User.objects.filter(name=username).first()
            if not user:
                return Response({'code':200, "message":"没有找到此用户"})
            password = User.objects.filter(pwd=pwd).first()
            if password:
                return Response({"code":200, "message":"登录成功"})
            else:
                return Response({'code':204,"message":"密码错误"})
        except Exception as e:
            print('错误>>', e)
            return Response({'code':500, 'message':'服务器错误'})


class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"